import lcd_engine from "@/lcd.engine.js";
import Vue from "vue";
import { cloneDeep, isNull } from "@/utils";
const { tooler, share, renderer } = lcd_engine;

// 创建editor的默认state
const createEditorState = function () {
  const _state = {
    // 全局变量
    variable: {},
    // 触发了restore事件
    restore: false,
    setterID: null,
    siderID: null,
    // 大屏配置schema
    schema: {
      // 关联关系
      graph: {},
      // 画布宽度
      width: renderer.width,
      // 画布高度
      height: renderer.height,
      // 视图id
      viewId: "",
      // 视图名称
      name: "",
      // 视图缩略图
      thumbnail: "",
      // 封面地址
      cover: "",
      // 组件信息 id => meta
      meta: {},
    },
    // 选中状态 0：组件 1：画板 2：其他
    status: "2",
    // 车道模型 布局算法 [0,0]: 左闭右闭 [0,1]：左闭右开 [1,0]：左开右闭 [1,1]：左开右开
    layout: [1, 1],
    scale: 1,
    getComponentList: [],
    // 下一步栈
    backStack: [],
    // 上一步栈
    forwardStack: [],
    // 组件选中状态
    selectStack: null,
    // 组件对应Key 关联配置项
    selectKey: null,
    // 保存最新的截图
    canvasImg: null,
    canvasStyle: {
      width: renderer.width,
      height: renderer.height,
    },
    selectCanvas: true, // 是否操作了截取封面操作
  };

  return _state;
};

// @override save操作
const EDITOR_SAVE = ($state, payload) => {
  console.log("EDITOR_SAVE", payload);
};

// @override preview操作
const EDITOR_PREVIEW = ($state, payload) => {
  console.log("EDITOR_PREVIEW", payload);
  localStorage.setItem("preview", JSON.stringify($state.getComponentList));
  localStorage.setItem("graph", JSON.stringify($state.schema.graph));
  localStorage.setItem("canvasStyle", JSON.stringify($state.canvasStyle));
  window.open(`${window.location.origin}/#/preview/${payload.params}`);
};

// variable操作
const EDITOR_VARIABLE = ($state, payload) => {
  const {key, value} = payload;
  console.log('EDITOR_VARIABLE', key, value)
  if(!key || !value) return;
  Vue.set($state.variable, key, value);
}

// graph操作
const EDITOR_GRAPH = ($state, payload) => {
  const {key, value} = payload;
  if(!key || !value) return;
  $state.schema.graph[key] = value;
}

// undo操作
const EDITOR_UNDO = ($state) => {
  const targetData = forwardAction($state);
  if (targetData) {
    const { id = null, key = null, DELETE = false } = targetData;
    /* 处理选中 */
    $state.selectStack = id;
    $state.selectKey = key;
    if ($state.status != "0") {
      $state.status = "0";
    }
    if (DELETE) {
      // 新增
      $state.getComponentList.push(targetData);
      return;
    }
    const idArr = $state.forwardStack.filter((e) => e.id === id);
    if (!idArr.length) {
      console.log(id);
      const index = $state.getComponentList.findIndex((e) => e.id === id);
      $state.getComponentList.splice(index, 1);
      backforward($state, index);
      return;
    }
    /* 处理移动 */
    if ($state.forwardStack.length) {
      const lastIndex = $state.forwardStack.findLastIndex((e) => e.id === id);
      const data = $state.forwardStack[lastIndex];
      const index = $state.getComponentList.findIndex((e) => e.id === data.id);
      Vue.set($state.getComponentList[index], "attr", { ...data.attr });
    }
  }
};

const forwardAction = ($state) => {
  if ($state.forwardStack.length) {
    const targetData = cloneDeep($state.forwardStack.pop());
    if (!targetData) return;
    $state.backStack.push({ ...targetData });
    return targetData;
  }
  return false;
};

// redo操作
const EDITOR_REDO = ($state) => {
  const targetData = backAction($state);
  if (targetData) {
    const { id = null, key = null, DELETE = false } = targetData;
    const index = $state.getComponentList.findIndex((e) => e.id === id);
    if (DELETE) {
      // 删除
      $state.getComponentList.splice(index, 1);
      backforward($state, index);
      return;
    }
    if (index == -1) {
      $state.getComponentList.push(cloneDeep(targetData));
    } else {
      /* 处理移动 */
      const idx = $state.getComponentList.findIndex(
        (e) => e.id === targetData.id
      );
      Vue.set($state.getComponentList[idx], "attr", { ...targetData.attr });
    }
    /* 处理选中 */
    $state.selectStack = id;
    $state.selectKey = key;
    if ($state.status != "0") {
      $state.status = "0";
    }
    $state.setterID = `lcd-setter-${key}~${id}`;
    $state.siderID = `lcd-sider-${key}~${id}`;
  }
};

const backAction = ($state) => {
  if ($state.backStack.length) {
    const targetData = cloneDeep($state.backStack.pop());
    if (!targetData) return;
    $state.forwardStack.push({ ...targetData });
    return targetData;
  }
  return false;
};

const backforward = ($state, index) => {
  if ($state.getComponentList.length) {
    $state.selectStack = $state.getComponentList[index - 1].id;
    $state.selectKey = $state.getComponentList[index - 1].key;
    $state.setterID = `lcd-setter-${$state.selectKey}~${$state.selectStack}`;
    $state.siderID = `lcd-sider-${$state.selectKey}~${$state.selectStack}`;
  } else {
    $state.status = "2";
    $state.selectStack = null;
    $state.selectKey = null;
    $state.setterID = null;
    $state.siderID = null;
  }
};

// reset操作
const EDITOR_RESET = ($state, payload) => {
  Object.assign($state, createEditorState());
};

// @override exit操作
const EDITOR_EXIT = ($state, payload) => {
  console.log("EDITOR_EXIT", payload);
};

// status操作
const EDITOR_STATUS = ($state, payload) => ($state.status = payload);

// layout操作
const EDITOR_LAYOUT = ($state, payload) => {
  $state.layout = payload;
};

// remove操作
const EDITOR_REMOVE = ($state) => {
  if (!$state.getComponentList.length) return;
  const index = $state.getComponentList.findIndex(
    (e) => e.id === $state.selectStack
  );
  const data = $state.getComponentList[index];
  $state.getComponentList.splice(index, 1);
  $state.forwardStack.push({ ...data, DELETE: true });
  // 处理选中
  if ($state.getComponentList.length) {
    const { id, key } =
      $state.getComponentList[$state.getComponentList.length - 1];
    $state.selectStack = id;
    $state.selectKey = key;
    $state.setterID = `lcd-setter-${key}~${id}`;
    $state.siderID = `lcd-sider-${key}~${id}`;
  } else {
    $state.status = "2";
    $state.selectStack = null;
    $state.selectKey = null;
    $state.setterID = null;
    $state.siderID = null;
  }
};

// meta操作
const EDITOR_META = ($state, payload) => {
  console.log("EDITOR_META", payload);
  $state.schema.meta = payload;
};

// name操作
const EDITOR_NAME = ($state, payload) => {
  console.log("EDITOR_NAME", payload);
  $state.schema.name = payload;
};

// viewId操作
const EDITOR_VIEW_ID = ($state, payload) => {
  console.log("EDITOR_VIEW_ID", payload);
  $state.schema.viewId = payload;
};

// thumbnail操作
const EDITOR_THUMBNAIL = ($state, payload) => {
  console.log("EDITOR_THUMBNAIL", payload);
  $state.schema.thumbnail = payload;
};

// cover操作
const EDITOR_COVER = ($state, payload) => {
  console.log("EDITOR_COVER", payload);
  $state.schema.cover = payload;
};

// shema操作
const EDITOR_SCHEMA = ($state, payload) => {
  console.log("EDITOR_SCHEMA", payload);
  $state.schema = payload;
};

// 放大缩小
const EDITOR_SCALE = ($state, payload) => ($state.scale = payload);

// 替换组件列表
const EDITOR_REPLACE_LIST = ($state, payload) => {
  $state.getComponentList = payload;
};

// 新增组件列表
const EDITOR_ADD_LIST = ($state, payload) => {
  const { id = null, key = null } = payload;
  if (!id) return;
  $state.getComponentList.push(payload);
  $state.forwardStack.push(payload);
  if ($state.backStack.length) {
    $state.backStack = [];
  }
  $state.selectStack = id;
  $state.selectKey = key;
  $state.setterID = `lcd-setter-${key}~${id}`;
  $state.siderID = `lcd-sider-${key}~${id}`;
};

// 更新组件列表
const EDITOR_UPDATE_LIST = ($state, payload) => {
  const { id = null, key, value, isRecord = null } = payload;
  if (!id || !key) return;
  const index = $state.getComponentList.findIndex((e) => e.id === id);
  const object = $state.getComponentList.find((e) => e.id === id);
  if (key == "attr") {
    // 不记录组件来回切换选中
    const MoveBoolean = Object.keys(value).every(
      (e) => value[e] == object.attr[e]
    );
    if (MoveBoolean) return;
  }
  object[key] = value;
  // 深拷贝
  const component = cloneDeep(object);
  console.log("EDITOR_UPDATE_LIST", component);
  // 使用$set修改index位置的变化
  Vue.set($state.getComponentList, index, component);
  if (key == "prop") return; // 不记录组件配置改动
  if (isRecord) {
    // 只记录画布上操作的 大小改变
    $state.forwardStack.push(component);
  }
};

// restore操作
const EDITOR_RESTORE = ($state, payload) => {
  const { id } = payload;
  const meta = $state.schema.meta[id];
  console.log("EDITOR_RESTORE", meta);
  $state.restore = true;
  setTimeout(() => {
    $state.restore = false;
  }, share.delay);
};

// 更新选中
const EDITOR_UPDATE_SELECT = ($state, payload) => {
  console.log("EDITOR_UPDATE_SELECT", payload);
  $state.selectStack = payload;
  if (payload) {
    $state.status = "0";
    $state.restore = true;
    const { key } = $state.getComponentList.find((e) => e.id == payload);
    $state.selectKey = key;
    $state.setterID = `lcd-setter-${key}~${payload}`;
    $state.siderID = `lcd-sider-${key}~${payload}`;
    setTimeout(() => {
      $state.restore = false;
    }, share.delay);
  } else if (isNull(payload)) {
    // 为null说明是点击的画板
    $state.status = "1";
  } else {
    $state.status = "2";
  }
};

const EDITOR_CANVASIMG = ($state, payload) => {
  console.log("EDITOR_CANVASIMG", payload);
  $state.canvasImg = payload;
};

const EDITOR_CANVASSTYLE = ($state, payload) => {
  $state.canvasStyle = payload;
  $state.schema.width = payload.width;
  $state.schema.height = payload.height;
};

const EDITOR_SELECT_CANVANS = ($state, payload) => {
  $state.selectCanvas = payload;
};

const createToolerMutations = function () {
  const _mutations = {};
  Object.entries(tooler).forEach(([key, content]) => {
    const { name } = content.trigger;
    switch (content.key.description) {
      case "save":
        _mutations[name] = EDITOR_SAVE;
        break;
      case "preview":
        _mutations[name] = EDITOR_PREVIEW;
        break;
      case "undo":
        _mutations[name] = EDITOR_UNDO;
        break;
      case "redo":
        _mutations[name] = EDITOR_REDO;
        break;
      case "exit":
        _mutations[name] = EDITOR_EXIT;
        break;
      default:
        break;
    }
  });

  return _mutations;
};

const mutations = {
  ...{
    handleVariable: EDITOR_VARIABLE,
    handleGraph: EDITOR_GRAPH,
    handleStatus: EDITOR_STATUS,
    handleLayout: EDITOR_LAYOUT,
    handleRestore: EDITOR_RESTORE,
    handleRemove: EDITOR_REMOVE,
    handleScale: EDITOR_SCALE,
    handleAddComponent: EDITOR_ADD_LIST,
    handleUpdateComponent: EDITOR_UPDATE_LIST,
    handleReplaceComponent: EDITOR_REPLACE_LIST,
    handleUpdateSelect: EDITOR_UPDATE_SELECT,
    handleCanvasImg: EDITOR_CANVASIMG,
    handleMeta: EDITOR_META,
    handleName: EDITOR_NAME,
    handleViewId: EDITOR_VIEW_ID,
    handleThumbnail: EDITOR_THUMBNAIL,
    handleCover: EDITOR_COVER,
    handleCanvasStyle: EDITOR_CANVASSTYLE,
    handleSchema: EDITOR_SCHEMA,
    handleReset: EDITOR_RESET,
    handleSelectCanvas: EDITOR_SELECT_CANVANS,
  },
  ...createToolerMutations(),
};

const state = {
  ...{},
  ...createEditorState(),
};

import * as components_store from './modules';

console.log('components_store', components_store)

export default {
  namespaced: true,
  modules: {
    ...components_store
  },
  state,
  mutations,
  actions: {},
};
